<?php
declare (strict_types = 1);
namespace app\admin\controller;

use think\Request;
use think\facade\{View, Session};
use think\exception\ValidateException;
use service\JsonService as Json;

use app\common\model\{Goods, GoodsCate, Sku, SkuValue, Img};
use app\common\validate\{GoodsValidate, GoodsCateValidate, SkuValidate, SkuValueValidate};

class GoodsController extends BaseController
{
    /**
     * 渲染商品列表页面
     */
    public function goods_list()
    {
        return view();
    }

    /**
     * 商品列表数据
     */
    public function goods_data()
    {
        $data = input('');

        try{
            validate(GoodsValidate::class)->scene('list')->check($data);
        }catch(ValidateException $e){
            return Json::fail($e->getError());
        }

        $where = [];

        /** 搜索条件 */
        if($data && isset($data['key'])){
            if(!empty($data['key']['name'])){
                $where[] = ['name', 'like', '%' . $data['key']['name'] . '%'];
            }
        }

        $list = Goods::getList($where, 1, $data['page'], $data['limit']);

        if($list === false) return Json::fail('暂无数据~');
        return Json::success('ok', $list, Goods::getNum($where));
    }

    /**
     * 渲染商品添加页面
     */
    public function goods_add()
    {
        $cate_list = GoodsCate::getList([]);
        $sku_list = Sku::getList([]);
        $sku_value_list = SkuValue::getList([]);

        View::assign('sku_list', $sku_list);
        View::assign('cate_list', $cate_list);
        View::assign('sku_value_list', $sku_value_list);
        return view();
    }

    /**
     * 商品添加
     */
    public function goods_add_data()
    {
        $data  = input('');

        $token = Session::get('token');

        // if($token['role'] === '超级管理员'){
        //     return '管理员不能添加商品';
        // }else{
        //     $data['shop_id'] = $token['id'];
        // }
        
        $data['small_img'] = request()->file('small_img');

        try{
            validate(GoodsValidate::class)->scene('add')->check($data);
        }catch(ValidateException $e){
            return Json::fail($e->getError());
        }

        $goodsImgBanner = json_decode($data['banner_img'], true);
        $goodsImgShow = json_decode($data['show_img'], true);
        unset($data['banner_img']);
        unset($data['show_img']);

        if(empty($goodsImgBanner)){
            return Json::fail('轮播图不能为空');
        }

        $data['small_img'] = fileUp($data['small_img'], 'goods');

        $sku_list = json_decode($data['sku_list'], true);

        /** 拼装商品sku */
        $str = '';
        $key = -1;
        $sku_list_data = [];
        foreach($sku_list as $val){
            if(strstr(array_key_first($val), 'sku[') !== false){
                $sku_info['sku'] = Sku::getVal(['id' => $val[array_key_first($val)]], 'name');
                $str = explode('sku[', array_key_first($val))[1];
                $key++;
            }

            if(strstr(array_key_first($val), 'sku_value[') !== false && explode('sku_value[', array_key_first($val))[1] === $str){
                $sku_info1['name']  = SkuValue::getVal(['id' => $val[array_key_first($val)]], 'name');
            }

            if(strstr(array_key_first($val), 'price_specs[') !== false && explode('price_specs[', array_key_first($val))[1] === $str){
                $sku_info1['price'] = $val[array_key_first($val)];
            }

            if(isset($sku_info1)) $sku_info['sku_value'] = $sku_info1;
            if(isset($sku_info)) $sku_list_data[$key] = $sku_info;
        }

        $sku_list_datas = [];
        $sku_str = '';
        $sku_key = -1;
        foreach($sku_list_data as $vv){
            $sku_infos = [];

            if($vv['sku'] === $sku_str){
                array_push($sku_list_datas[$sku_key]['sku_value'], $vv['sku_value']);
                continue;
            }else{
                $sku_str = $sku_infos['sku'] = $vv['sku'];
                $sku_infos['sku_value'][] = $vv['sku_value'];
                $sku_key++;
            }

            $sku_list_datas[] = $sku_infos;
        }

        $data['sku_list'] = json_encode($sku_list_datas);

        $flag = Goods::add($data);

        if($flag === false){
            return Json::fail('添加失败');
        }

        /** 轮播图 */
        $goodsImg = [];
        foreach($goodsImgBanner as $key => $val){
            $bannerImgArr = [
                'img'         => $val['url'],
                'obj_type'    => 1,
                'obj_id'      => $flag->id,
                'obj_cate'    => 1,
                'sort'        => $val['sort'],
                'create_time' => time()
            ];
            
            $goodsImg[] = $bannerImgArr;
        }

        /** 详情图 */
        foreach($goodsImgShow as $k => $v){
            $showImgArr = [
                'img'         => $v['url'],
                'obj_type'    => 1,
                'obj_id'      => $flag->id,
                'obj_cate'    => 2,
                'sort'        => $val['sort'],
                'create_time' => time()
            ];
            
            $goodsImg[] = $showImgArr;
        }

        /** 添加图片 */
        Img::addAll($goodsImg);
        return Json::success('添加成功');
    }

    /**
     * 多图上传
     */
    public function imgUpMany()
    {
        $file = request()->file('file');

        $imgUrl = fileUp($file, 'goods');
        return Json::success('ok', $imgUrl);
    }

    /**
     * 商品图片删除
     */
    public function del_img()
    {
        $data = input("post.url_img");

        $res = Img::where("id", $data)->delete();ff($data);

        if(!$res) return Json::fail('删除失败');
        return Json::success('删除成功');
    }

    /**
     * 渲染商品修改页面
     */
    public function goods_edit()
    {
        $data = input('');
        $cate_list = GoodsCate::getList([]);
        $info = Goods::getFind(['id' => $data['id']]);

        $banner_img = Img::getList(['obj_id' => $info['id'], 'obj_type' => 1, 'obj_cate' => 1], '*', 'sort');
        $show_img = Img::getList(['obj_id' => $info['id'], 'obj_type' => 1, 'obj_cate' => 2], '*', 'sort');

        if($banner_img === false){
            $info['banner_img'] = [];
        }else{
            $info['banner_img'] = $banner_img;
        }

        if($show_img === false){
            $info['show_img'] = [];
        }else{
            $info['show_img'] = $show_img;
        }

        $type = [1 => '普通商品', 2 => '佣金商品', 3 => '红包商品', 4 => '积分商品'];

        View::assign('info', $info);
        View::assign('type', $type);
        View::assign('cate_list', $cate_list);
        return view();
    }

    /**
     * 商品信息修改
     */
    public function goods_edit_data()
    {   
        $data = input('');
        
        $data['small_img'] = request()->file('small_img');

        if($data['small_img']){
            $field = 'edit_img';
        }else{
            $field = 'edit';
        }

        try{
            validate(GoodsValidate::class)->scene($field)->check($data);
        }catch(ValidateException $e){
            return Json::fail($e->getError());
        }

        $goodsImgBanner = json_decode($data['banner_img'], true);
        $goodsImgShow = json_decode($data['show_img'], true);
        unset($data['banner_img']);
        unset($data['show_img']);

        if(empty($goodsImgBanner)){
            return Json::fail('轮播图不能为空');
        }

        /** 修改商品 */
        if($data['small_img']){
            $data['small_img'] = fileUp($data['small_img'], 'goods');
        }else{
            unset($data['small_img']);
        }

        $flag = Goods::edit($data);

        if($flag === false) return Json::fail('修改失败');

        /** 轮播图 */
        $goodsImg = [];
        foreach($goodsImgBanner as $key => $val){
            $bannerImgArr = [
                'img'         => $val['url'],
                'obj_type'    => 1,
                'obj_id'      => $data['id'],
                'obj_cate'    => 1,
                'sort'        => $val['sort'],
                'create_time' => time()
            ];
            
            $goodsImg[] = $bannerImgArr;
        }

        /** 详情图 */
        foreach($goodsImgShow as $k => $v){
            $showImgArr = [
                'img'         => $val['url'],
                'obj_type'    => 1,
                'obj_id'      => $data['id'],
                'obj_cate'    => 2,
                'sort'        => $val['sort'],
                'create_time' => time()
            ];
            
            $goodsImg[] = $showImgArr;
        }

        Img::del(['obj_id' => $data['id']]);

        /** 添加图片 */
        Img::addAll($goodsImg);
        return Json::success('修改成功');
    }




    /**
     * 渲染属性值列表页面
     */
    public function sku_list()
    {
        return view();
    }

    /**
     * 属性列表数据
     */
    public function sku_data()
    {
        $data = input('');

        try{
            validate(SkuValidate::class)->scene('list')->check($data);
        }catch(ValidateException $e){
            return Json::fail($e->getError());
        }

        $where = [];

        /** 搜索条件 */
        if($data && isset($data['key'])){
            if(!empty($data['key']['name'])){
                $where[] = ['name', 'like', '%' . $data['key']['name'] . '%'];
            }
        }

        $list = Sku::getList($where, 1, $data['page'], $data['limit']);

        if($list === false) return Json::fail('暂无数据~');
        return Json::success('ok', $list, Sku::getNum($where));
    }

    /**
     * 渲染属性添加页面
     */
    public function sku_add()
    {
        return view();
    }

    /**
     * 属性添加
     */
    public function sku_add_data()
    {
        $data = input('');

        try{
            validate(SkuValidate::class)->scene('add')->check($data);
        }catch(ValidateException $e){
            return Json::fail($e->getError());
        }

        $list = Sku::add($data);

        if($list === false) return Json::fail('添加失败');
        return Json::success('添加成功');
    }

    /**
     * 属性修改
     */
    public function sku_edit_data()
    {
        $data = input('');
        $datas = ['id' => $data['id'], $data['field'] => $data['value']];

        try{
            validate(SkuValidate::class)->scene('edit')->check($datas);
        }catch(ValidateException $e){
            return Json::fail($e->getError());
        }

        $list = Sku::edit($datas);

        if($list === false) return Json::fail('修改失败');
        return Json::success('修改成功');
    }

    /**
     * 删除属性
     */
    public function sku_del()
    {
        $data = input('');

        try{
            validate(SkuValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            return Json::fail($e->getError());
        }

        $flag = Sku::destroy($data['id']);

        if($flag === false) return Json::fail('删除失败');
        return Json::success('删除成功');
    }




    /**
     * 渲染属性值列表页面
     */
    public function sku_value_list()
    {
        return view();
    }

    /**
     * 属性值列表数据
     */
    public function sku_value_data()
    {
        $data = input('');

        try{
            validate(SkuValueValidate::class)->scene('list')->check($data);
        }catch(ValidateException $e){
            return Json::fail($e->getError());
        }

        $where = [];

        /** 搜索条件 */
        if($data && isset($data['key'])){
            if(!empty($data['key']['name'])){
                $where[] = ['name', 'like', '%' . $data['key']['name'] . '%'];
            }
        }

        $list = SkuValue::getList($where, 1, $data['page'], $data['limit'], '*', 'sku_id');

        if($list === false) return Json::fail('暂无数据~');
        return Json::success('ok', $list, SkuValue::getNum($where));
    }

    /**
     * 渲染属性值添加页面
     */
    public function sku_value_add()
    {
        $sku_list = Sku::getList([], 0);

        View::assign('sku_list', $sku_list);
        return view();
    }

    /**
     * 属性值添加
     */
    public function sku_value_add_data()
    {
        $data = input('');

        try{
            validate(SkuValueValidate::class)->scene('add')->check($data);
        }catch(ValidateException $e){
            return Json::fail($e->getError());
        }

        $list = SkuValue::add($data);

        if($list === false) return Json::fail('添加失败');
        return Json::success('添加成功');
    }

    /**
     * 属性值修改
     */
    public function sku_value_edit_data()
    {
        $data = input('');
        $datas = ['id' => $data['id'], $data['field'] => $data['value']];

        try{
            validate(SkuValueValidate::class)->scene('edit')->check($datas);
        }catch(ValidateException $e){
            return Json::fail($e->getError());
        }

        $list = SkuValue::edit($datas);

        if($list === false) return Json::fail('修改失败');
        return Json::success('修改成功');
    }

    /**
     * 删除属性值
     */
    public function sku_value_del()
    {
        $data = input('');

        try{
            validate(SkuValueValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            return Json::fail($e->getError());
        }

        $flag = SkuValue::destroy($data['id']);

        if($flag === false) return Json::fail('删除失败');
        return Json::success('删除成功');
    }

    /**
     * 获取属性
     */
    public function spec_sku()
    {
        $list = Sku::getList([], 0);

        if($list === false) return Json::fail('暂无数据~');
        return Json::success('ok', $list);
    }

    /**
     * 获取属性对应的属性值
     */
    public function sku_value()
    {
        $data = input('');

        $list = SkuValue::getList(['sku_id' => $data['sku_id']], 0, 0, 0, '*', 'sku_id');

        if($list === false) return Json::fail('暂无数据~');
        return Json::success('ok', $list);
    }




    /**
     * 渲染分类列表页面
     */
    public function cate_list()
    {
        return view();
    }

    /**
     * 分类列表数据
     */
    public function cate_data()
    {
        $data = input('');

        try{
            validate(GoodsCateValidate::class)->scene('list')->check($data);
        }catch(ValidateException $e){
            return Json::fail($e->getError());
        }

        $where = [];

        /** 搜索条件 */
        if($data && isset($data['key'])){
            if(!empty($data['key']['name'])){
                $where[] = ['name', 'like', '%' . $data['key']['name'] . '%'];
            }
        }

        $list = GoodsCate::getList($where, 1, $data['page'], $data['limit']);

        if($list === false) return Json::fail('暂无数据~');
        return Json::success('ok', $list, GoodsCate::getNum($where));
    }

    /**
     * 渲染分类添加页面
     */
    public function cate_add()
    {
        return view();
    }

    /**
     * 分类添加
     */
    public function cate_add_data()
    {
        $data = input('');

        try{
            validate(GoodsCateValidate::class)->scene('add')->check($data);
        }catch(ValidateException $e){
            return Json::fail($e->getError());
        }

        $list = GoodsCate::add($data);

        if($list === false) return Json::fail('添加失败');
        return Json::success('添加成功');
    }

    /**
     * 分类修改
     */
    public function cate_edit_data()
    {
        $data = input('');
        $datas = ['id' => $data['id'], $data['field'] => $data['value']];

        try{
            validate(GoodsCateValidate::class)->scene('add')->check($datas);
        }catch(ValidateException $e){
            return Json::fail($e->getError());
        }

        $list = GoodsCate::edit($datas);

        if($list === false) return Json::fail('修改失败');
        return Json::success('修改成功');
    }

    /**
     * 删除分类
     */
    public function cate_del()
    {
        $data = input('');

        try{
            validate(GoodsCateValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            return Json::fail($e->getError());
        }

        $flag = GoodsCate::destroy($data['id']);

        if($flag === false) return Json::fail('删除失败');
        return Json::success('删除成功');
    }
}
